package com.ruizhong.integratedmediawithoutc.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruizhong.integratedmediawithoutc.server.WebSocketServer;


import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class TCPUtil {

    public static String pushStreamServerIp = "192.168.3.254";

    public static String getPushStreamServerIp() {
        return pushStreamServerIp;
    }

    public static void setPushStreamServerIp(String pushStreamServerIp) {
        TCPUtil.pushStreamServerIp = pushStreamServerIp;
    }

    public static Map<String,Object> send(Map<String,Object> conditionMap) {
        final String SERVER_IP = pushStreamServerIp;
        final int PORT = 20380;

        try (
                Socket socket = new Socket(SERVER_IP, PORT);
                OutputStream outputStream = socket.getOutputStream();
                DataOutputStream dataOut = new DataOutputStream(outputStream);
                InputStream inputStream = socket.getInputStream();
        ) {
//            System.out.println("已连接到服务器");

            // 1. 准备并发送数据
            ObjectMapper objectMapper = new ObjectMapper();
            String userInput = objectMapper.writeValueAsString(conditionMap);
//            System.out.println("JSON 字符串: " + userInput);

            byte[] dataBytes = userInput.getBytes(StandardCharsets.US_ASCII);

            // 发送长度(小端序)
            ByteBuffer buffer = ByteBuffer.allocate(4);
            buffer.order(ByteOrder.LITTLE_ENDIAN);
            buffer.putInt(dataBytes.length);
            dataOut.write(buffer.array());
            dataOut.flush();

            // 发送数据
            dataOut.write(dataBytes);
            dataOut.flush();
//            System.out.println("已发送数据：" + userInput);

            // 2. 接收服务器响应
            // 先读取4字节长度(小端序)
            byte[] lengthBytes = new byte[4];
            int bytesRead = inputStream.read(lengthBytes);
            if (bytesRead != 4) {
                throw new IOException("未能读取完整的长度头");
            }

            int responseLength = ByteBuffer.wrap(lengthBytes)
                    .order(ByteOrder.LITTLE_ENDIAN)
                    .getInt();
//            System.out.println("响应数据长度: " + responseLength + "字节");

            // 读取响应内容
            byte[] responseBytes = new byte[responseLength];
            int totalRead = 0;
            while (totalRead < responseLength) {
                int read = inputStream.read(responseBytes, totalRead, responseLength - totalRead);
                if (read == -1) {
                    throw new IOException("连接意外终止");
                }
                totalRead += read;
            }

            // 3. 解码并处理响应
            String response = new String(responseBytes, "GB2312");
//            System.out.println("完整服务器响应: " + response);

            objectMapper = new ObjectMapper();
                Map<String, Object> map = objectMapper.readValue(response, Map.class);
          return map;
        } catch (UnknownHostException e) {
            System.err.println("无法找到主机: " + SERVER_IP);
        } catch (IOException e) {
            System.err.println("I/O异常: " + e.getMessage());
        } catch (Exception e) {
            System.err.println("其他异常: " + e.getMessage());
        }
        return null;
    }

    public static void sendWithReplies(Map<String,Object> conditionMap,String wsToken){
        final String SERVER_IP = pushStreamServerIp;
        final int PORT = 20380;
        long startTime = System.currentTimeMillis();
        try (
                Socket socket = new Socket(SERVER_IP, PORT);
                OutputStream outputStream = socket.getOutputStream();
                DataOutputStream dataOut = new DataOutputStream(outputStream);
                InputStream inputStream = socket.getInputStream();
        ) {
            System.out.println("已连接到服务器");

            // 1. 准备并发送数据
            ObjectMapper objectMapper = new ObjectMapper();
            String userInput = objectMapper.writeValueAsString(conditionMap);
            System.out.println("JSON 字符串: " + userInput);

            byte[] dataBytes = userInput.getBytes(StandardCharsets.US_ASCII);

            // 发送长度(小端序)
            ByteBuffer buffer = ByteBuffer.allocate(4);
            buffer.order(ByteOrder.LITTLE_ENDIAN);
            buffer.putInt(dataBytes.length);
            dataOut.write(buffer.array());
            dataOut.flush();

            // 发送数据
            dataOut.write(dataBytes);
            dataOut.flush();
            System.out.println("已发送数据：" + userInput);

            // 2. 接收服务器响应
            // 先读取4字节长度(小端序)
            byte[] lengthBytes = new byte[4];
            int bytesRead ;
            while((bytesRead = inputStream.read(lengthBytes))>0){
                if (bytesRead != 4) {
                    throw new IOException("未能读取完整的长度头");
                }

                int responseLength = ByteBuffer.wrap(lengthBytes)
                        .order(ByteOrder.LITTLE_ENDIAN)
                        .getInt();
                System.out.println("响应数据长度: " + responseLength + "字节");

                // 读取响应内容
                byte[] responseBytes = new byte[responseLength];
                int totalRead = 0;
                while (totalRead < responseLength) {
                    int read = inputStream.read(responseBytes, totalRead, responseLength - totalRead);
                    if (read == -1) {
                        throw new IOException("连接意外终止");
                    }
                    totalRead += read;
                }

                // 3. 解码并处理响应
                String response = new String(responseBytes, "GB2312");
                System.out.println("完整服务器响应: " + response);
                if (response.contains("Successful! Please restart the RTSP service to update.")){
                    break;
                }
                long currentTimeMillis = System.currentTimeMillis();

                objectMapper = new ObjectMapper();
                Map<String, Object> map = objectMapper.readValue(response, Map.class);
                Map<String, Object> resMap = (Map<String, Object>) map.get("data");
                int progress = (int)resMap.get("progress");
               if (progress== 0){
                   continue;
               }
                long elapsedTime = currentTimeMillis - startTime;
                double restTime = (double)((((elapsedTime) * 100) /  progress)) - (elapsedTime);
                WSResult<Map<String,Object>> wsResult = new WSResult<>();
                HashMap<String, Object> wsResultMap = new HashMap<>();
                if (restTime<=60*1000){
                    wsResultMap.put("rest","预计剩余 "+(int)(restTime/1000)+" 秒");
                }else{
                    wsResultMap.put("rest","预计剩余 "+(int)((restTime/1000)/60)+" 分钟");
                }
                wsResultMap.put("type",0);
                wsResultMap.put("progress", progress);
                String[] file_paths = resMap.get("file_path").toString().split("\\\\");
                wsResultMap.put("file", file_paths[file_paths.length-1]);
                wsResult.setData(wsResultMap);
                WebSocketServer.sendInfo(wsResult,wsToken);
            }
            System.out.println("回复结束");
            WSResult<Map<String,Object>> wsResult = new WSResult<>();
            HashMap<String, Object> wsResultMap = new HashMap<>();
            wsResultMap.put("type",1);
            wsResult.setData(wsResultMap);
            WebSocketServer.sendInfo(wsResult,wsToken);
        } catch (UnknownHostException e) {
            System.err.println("无法找到主机: " + SERVER_IP);
        } catch (IOException e) {
            System.err.println("I/O异常: " + e.getMessage());
        } catch (Exception e) {
            System.err.println("其他异常: " + e.getMessage());
        }

    }
}
